import Vue from 'vue'
import Router from 'vue-router'
import Layout from '../layout'
Vue.use(Router)
export const constantRoutes = [
  {
    path: '/',
    component: () => import('@/views/HomeView/index.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/HomeView/index.vue')
  },
]

const createRouter = () => new Router({
  routes: constantRoutes
})

const router = createRouter()

// 路由抛出异常时候的全局监听
router.onError((error) => {
  // 前端未找到菜单对应前端文件路径，请检查菜单是否正确或者前端文件是否缺失
  if (error.message.includes('Cannot find module')) {
    console.log('前端未找到菜单对应前端文件路径，请检查菜单是否正确或者前端文件是否缺失')
  }
})
router.beforeEach((to, from, next) => {
  console.log(to, from)
  next()
})

// const path = '@/views'

const requireComponent = require.context(
  // 其组件目录的相对路径
  '@/views',
  // 是否查询其子目录
  true,
  // 匹配基础组件文件名的正则表达式
  /\.vue$/
)
const asyncRoutes = [{
    path: '/dashboard',
    component: Layout,
    children: []
}]
// 动态添加路由
requireComponent.keys().forEach(fileName => {
  if (fileName.includes('index.vue') && !fileName.includes('HomeView')) {
    asyncRoutes[0].children.push({
      path: fileName.replace('./', '/').replace('View/index.vue', ''),
      component: () => import(`@/views${fileName.replace('./', '/')}`),
    })
  }
})
router.addRoutes(asyncRoutes)
export default router
